package cn.zyx.pay.controller;

import cn.zyx.order.domain.AdoptOrder;
import cn.zyx.order.domain.ProductOrder;
import cn.zyx.order.service.IAdoptOrderService;
import cn.zyx.order.service.IProductOrderService;
import cn.zyx.pay.constants.PayConstants;
import cn.zyx.pay.domain.AlipayInfo;
import cn.zyx.pay.domain.PayBill;
import cn.zyx.pay.service.IAlipayInfoService;
import cn.zyx.pay.service.IPayBillService;
import cn.zyx.pay.utils.AlipayConfig;
import cn.zyx.quartz.service.IQuartzService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class AlipayController {

    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IAlipayInfoService alipayInfoService;
    @Autowired
    private IAdoptOrderService adoptOrderService;
    @Autowired
    private IProductOrderService productOrderService;
    @Autowired
    private IQuartzService quartzService;

    @PostMapping("/notify")
    public void notify(HttpServletRequest request){
        System.out.println("为什么不能异步回调啊!!!");
        //获取支付宝POST过来反馈信息
        try {
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                valueStr = new String(valueStr);
                params.put(name, valueStr);
            }

            // 从请求头里面获取支付单号
            String unionPaySn = params.get("out_trade_no");
            // 根据支付单号查询对应的支付单
            PayBill payBill = payBillService.loadByUnionPaySn(unionPaySn);
            if (payBill != null){
                // 通过支付账单的商店id获取账单信息
                AlipayInfo alipayInfo = alipayInfoService.getByShopId(payBill.getShop_id());
                // 身份校验 -- 确认身份
                boolean signVerified = AlipaySignature.rsaCheckV1(params,
                        alipayInfo.getAlipay_public_key(),
                        AlipayConfig.charset,
                        AlipayConfig.sign_type); //调用SDK验证签名

                if(signVerified) {//验证成功
                    //商户订单号
                    String out_trade_no = unionPaySn;

                    //支付宝交易号 -- 支付宝流水号
                    String trade_no = request.getParameter("trade_no");

                    //交易状态
                    String trade_status = request.getParameter("trade_status");

                    if(trade_status.equals("TRADE_FINISHED")){ // 用户确认交易

                    }else if (trade_status.equals("TRADE_SUCCESS")){    // 支付宝交易成功
                        // 修改支付单状态
                        payBill.setState(1); // 已支付
                        payBill.setUpdateTime(new Date());
                        payBillService.update(payBill);
                        // 修改对应的订单状态
                        String businessType = payBill.getBusinessType();
                        if (PayConstants.BUSINESS_TYPE_ADOPT.equals(businessType)){ // 领养订单
                            Long businessKey = payBill.getBusinessKey();
                            AdoptOrder adoptOrder = adoptOrderService.getById(businessKey);
                            adoptOrder.setState(1);         // 已完成
                            adoptOrderService.update(adoptOrder);
                        }else if (PayConstants.BUSINESS_TYPE_PRODUCT.equals(businessType)){ // 服务订单
                            Long businessKey = payBill.getBusinessKey(); // 获取业务键
                            ProductOrder productOrder = productOrderService.getById(businessKey); // 通过业务键查询到当前服务订单信息
                            productOrder.setState(1);   // 修改状态为已完成
                            productOrderService.update(productOrder);   // 修改数据库数据
                        }
                        // 移除当前订单的定时任务
                        quartzService.removeQuartz(out_trade_no);
                    }
                }else {//验证失败
                    System.out.println("fail");
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
